package LeedCode_BinaryTree;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:利用中序遍历和后序遍历创建二叉树
 * User: 阿宾
 * Date: 2024-11-27
 * Time: 10:10
 */
public class Demo10 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }
    //方法2
    public int postIndex;
    private int findIndex(int[] inorder,int inbegin,int inend,int key){
        for (int i = inbegin; i <= inend; i++) {
            if(inorder[i] == key){
                return i;
            }
        }
        return -1;
    }
    private TreeNode buildTreeBuild(int[] inorder, int[] postorder,int inbegin,int inend){

        if(inbegin > inend){
            return null;
        }
        //根据后序指针创建根节点
        TreeNode root = new TreeNode(postorder[postIndex]);
        int inIndex = findIndex(inorder,inbegin,inend,postorder[postIndex]);
        if(inIndex == -1){
            return null;
        }
        postIndex--;
        root.right = buildTreeBuild(inorder,postorder,inIndex+1,inend);
        root.left = buildTreeBuild(inorder,postorder,inbegin,inIndex-1);


        return root;
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {

        postIndex = postorder.length-1;
        return buildTreeBuild(inorder,postorder,0,inorder.length-1);

    }



    //方法1
    public TreeNode buildTree1(int[] inorder, int[] postorder) {
        if(inorder.length == 0 || postorder.length == 0){
            return null;
        }
        int index = -1;
        //创建根节点
        TreeNode root = new TreeNode(postorder[postorder.length-1]);
        //寻找中序遍历分割点
        for (int i = 0; i < inorder.length; i++) {
            if(inorder[i] == postorder[postorder.length-1]){
                index = i;
                break;
            }
        }
        //分割中序遍历
        int[] Leftinorder = Arrays.copyOfRange(inorder,0,index);
        int[] Rightinorder = Arrays.copyOfRange(inorder,index+1,inorder.length);

        //分割后序遍历
        int[] Leftpostorder = Arrays.copyOfRange(postorder,0,Leftinorder.length);
        int[] Rightpostorder = Arrays.copyOfRange(postorder,Leftinorder.length,postorder.length-1);

        root.left = buildTree1(Leftinorder,Leftpostorder);
        root.right = buildTree1(Rightinorder,Rightpostorder);

        return root;
    }
    public static void main(String[] args) {

    }
}
